import { defineStore } from 'pinia'
import { w3cwebsocket } from 'websocket'
import { getToken } from '@/store/modules/auth/helper';
interface WebSocketState {
  isConnected: boolean,
  socket?: w3cwebsocket,
  resData: any[],
  isContext: false,
}

export const useWebSocketStore = defineStore('websocket-store', {
  state: (): WebSocketState => ({
    isConnected: false,
    socket: undefined,
    resData: [],
    isContext: false,
  }),
  actions: {
    connect() {
      let token = 'Bearer ' + getToken();
      const wsUrl = `${import.meta.env.VITE_APP_API_WS_URL}/websocket?Authorization=${token}`
      const socket: w3cwebsocket = new w3cwebsocket(wsUrl)

      socket.onopen = () => {
        this.isConnected = true
        this.socket = socket
        // // 设置心跳包定时器
        // setInterval(() => {
        //   if (this.socket) {
        //     this.socket.send('ping')
        //   }
        // }, 10000) // 每隔 10 秒发送一次心跳包
      }

      socket.onclose = () => {
        this.isConnected = false
        this.socket = undefined
      }

      socket.onerror = (error: Event) => {
        console.error('WebSocket error:', error)
      }
      return socket
    },
    send(message: string, callback: (data: string) => void) {
      if (this.isConnected && this.socket) {
        this.resData = [];
        let param = {
          systemMessage: message,
          isConnected: this.isConnected,
        };
        this.socket.send(JSON.stringify(param));
        this.socket.onmessage = (event: MessageEvent) => {
          if (event.data.toString().includes('DONE')) {
            callback('done')
          } else {
            let json = { content: '' }
            json = JSON.parse(event.data)
            this.resData.push(json)
            let data = this.resData.map(it => { return it.content }).join('')
            callback(data)
          }
        }
      } else {
        console.error('WebSocket is not connected!')
      }
    },
    close() {
      if (this.isConnected && this.socket) {
        this.socket.close()
        this.socket = undefined
      } else {
        console.error('WebSocket is not connected!')
      }
    }
  }
})